package action;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;

import service.ProductService;
import action.form.ProductAddActionForm;

import com.opensymphony.xwork2.ActionSupport;

@Scope("request")
@ParentPackage(value = "default")
@Results(
    {
        @Result(name = "success", location = "productAdd.jsp"),
        @Result(name = "productList", location = "index.jsp")
    }
)
public class ProductAddAction extends ActionSupport implements ServletRequestAware {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = -9185527398118778044L;

	@Autowired
	private ProductService productService;
	
	@Autowired
	private ProductAddActionForm productAddActionForm;
	
	private HttpServletRequest request;
	
	@Action("/productAdd")
	@Override
	public String execute() throws Exception {
		String id = getRequest().getParameter("id");
		if (StringUtils.isNotBlank(id)) {
			if (StringUtils.isNumeric(id)) {
				// TODO process edit mode in this block
				productAddActionForm.setId(Integer.valueOf(id));
				// TODO get product by product id to show in edit form
			} else {
				return "productList";
			}
		}
		// TODO if id is null then it is insert mode
		
		return SUCCESS;
	}
	
	@Action("/productInsert")
	public String productInsert() {
		// TODO process insert action here
		// TODO after insert successfully then return to product list
		// TODO alert error when insert fail
		return "";
	}
	@Action("/productEdit")
	public String productEdit() {
		// TODO process edit product action here
		// TODO after edit successfully return to product list
		// TODO alert error when edit fail
		return "";
	}

	public void setProductAddActionForm(
			ProductAddActionForm productAddActionForm) {
		this.productAddActionForm = productAddActionForm;
	}
	
	public ProductAddActionForm getProductAddActionForm() {
		return productAddActionForm;
	}

	@Override
	public void setServletRequest(HttpServletRequest arg0) {
		this.request = arg0;
		
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}
	
}
